//app.js
import { 
  getStringFromFile,
  saveStringToFile,
 } from "./utils/util";
 import { 
  USER_FILE_NAME,
  VERSION_FILE_NAME,
  APP_FILE_NAME,
  } from "./constant/constant";

App({
  onLaunch: function () {
    this.initData();
  },
  onShow() {
    if (!this.globalData.userId || this.globalData.userId == null || this.globalData.userId.length == 0) {
      this.initLoginData();
    }
    if (this.globalData.navBarHeight == 0) {
      this.initSystemData();
    }
    if (!this.globalData.checkLocalVersion) {
      this.checkLocalVersion();
    }
    this.checkLocalAppToken();
  },
  onHide() {},
  onError(msg) {},
  globalData: {
    userInfo: null,
    cookieStr: '',
    isLogin: false,
    userId: null,
    navBarHeight: 0, // 导航栏高度
    menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
    menuBotton: 0, // 胶囊距底部间距（保持底部间距一致）
    menuHeight: 0, // 胶囊高度（自定义内容可与胶囊高度保证一致）
    menuWidth: 0,
    menuLeft: 0,
    statusBarHeight: 0,
    screenWidth: 0,
    screenHeight: 0,
    windowHeight: 0,
    windowWidth: 0,
    version: '0.108',
    versionCheckPassed: false,
    appToken: 'ccbf55b0eb2c55fd31634585b7f856aa9d9067e4',
    checkPosition: '0',
  },

  initData: function () {
    this.initSystemData();
    this.initLoginData();
  },

  initSystemData: function () {
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    // 胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    // 导航栏高度 = 状态栏到胶囊的间距（胶囊距上距离-状态栏高度） * 2 + 胶囊高度 + 状态栏高度
    this.globalData.navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + menuButtonInfo.height + systemInfo.statusBarHeight;
    this.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
    this.globalData.menuBotton = menuButtonInfo.top - systemInfo.statusBarHeight;
    this.globalData.menuHeight = menuButtonInfo.height;
    this.globalData.menuWidth = menuButtonInfo.width;
    this.globalData.menuLeft = menuButtonInfo.left;
    this.globalData.statusBarHeight = systemInfo.statusBarHeight;
    this.globalData.screenHeight = systemInfo.screenHeight;
    this.globalData.screenWidth = systemInfo.screenWidth;
    this.globalData.windowHeight = systemInfo.windowHeight;
    this.globalData.windowWidth = systemInfo.windowWidth;
  },

  initLoginData: function () {
    var cookies = wx.getStorageSync('cookie');
    if (cookies) {
      this.globalData.cookieStr = cookies;
      this.globalData.isLogin = true;
      var userId = wx.getStorageSync('userId');
      this.globalData.userId = userId;
    } else {
      var fsm = wx.getFileSystemManager();
      var path = wx.env.USER_DATA_PATH + '/' + USER_FILE_NAME;
      var that = this;
      fsm.readFile({
        filePath: path,
        encoding: 'utf-8',
        success: function (e) {
          var data = e.data;
          if (data) {
            var userId = data.substring(data.indexOf('=') + 1, data.indexOf(';'));
            var cookies = data.substring(data.indexOf('oscid='));
            that.globalData.cookieStr = cookies;
            that.globalData.isLogin = true;
            that.globalData.userId = userId;
          }
        },
        fail: function (e) {
          console.log(e);
        }
      });
    }
  },

  checkLocalVersion: function () {
    var fsm = wx.getFileSystemManager();
    var path = wx.env.USER_DATA_PATH + '/' + VERSION_FILE_NAME;
    var that = this;
    fsm.readFile({
      filePath: path,
      encoding: 'utf-8',
      success: function (e) {
        var version = e.data;
        if(version && version == that.globalData.version){
          that.globalData.versionCheckPassed = true;
          that.globalData.checkPosition = "1";
        } else {
          that.checkAppInfo();
        }
      },
      fail: function (e) {
        that.checkAppInfo();
      }
    });
  },

  checkAppInfo: function () {
    var that = this;
    wx.cloud.init();
    const db = wx.cloud.database();
    db.collection('version').doc('e62469b25fd0efb101379df74d93f1e6').get({
      success: function(res) {
        // res.data 包含该记录的数据
        console.log(res.data);
        if(res.data.version == that.globalData.version && !res.data.pass){

        } else {
          that.globalData.checkPosition = "2";
          that.globalData.versionCheckPassed = true;
          saveStringToFile(res.data.version, VERSION_FILE_NAME);
        }
      },
      fail: function(res){
        console.log('---db err: ' + res);
      }
    });
  },


  checkLocalAppToken: function(){
    var appTokenInfo = getStringFromFile(APP_FILE_NAME);
    if(appTokenInfo){
      var index = appTokenInfo.indexOf(';');
      var appToken = appTokenInfo.substring(0, index);
      var dateString = appTokenInfo.substring(index+1);
      var currentDateString = this.getCurrentDateString();
      if(appToken && (appToken != this.globalData.appToken || dateString != currentDateString)){
        this.globalData.appToken = appToken;
      } else if(!appToken || !dateString) {
        this.checkAppToken();
      }
    } else {
      this.checkAppToken();
    }
  },

  checkAppToken: function(){
    var that = this;
    wx.cloud.init();
    const db = wx.cloud.database();
    db.collection('version').doc('a8831daa5fe1e26c007c3eed465747f0').get({
      success: function(res) {
        // res.data 包含该记录的数据
        console.log(res.data);
        var token = res.data.appToken;
        if(token){
          that.globalData.appToken = token;
          var dateString = that.getCurrentDateString();
          saveStringToFile(token + ';' + dateString, APP_FILE_NAME);
        }
      },
      fail: function(res){
        console.log('---db err: ' + res);
      }
    });
  },
  
  getCurrentDateString: function(){
    var date = new Date(); //返回当前时间对象
    var dateString = date.getFullYear() + '' + date.getMonth() + '' + date.getDate();
    return dateString;
  }
})